package com.bjfu.intelligentrecognizeserver.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

@RestController
public class FileDownloadController {
    private static final Logger LOG = LoggerFactory.getLogger(FileDownloadController.class);
    private static final String BASE_DIR = "C:/Users/17805/Desktop/user_photo/";

    @RequestMapping("/downloadFile")
    public ResponseEntity<Resource> downloadFile(@RequestParam("filename") String filename
            , @RequestHeader(value = "Range", required = false) String rangeHeader) {
        LOG.info("downloadFile filename: {}", filename);
        String path = BASE_DIR + filename;
        File file = new File(path);
        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }

        long fileSize = file.length();
        long rangeStart = 0;
        if (rangeHeader != null && rangeHeader.startsWith("bytes")) {
            rangeStart = Long.parseLong(rangeHeader.split("=")[1].split("-")[0]);
        }

        long rangeEnd = fileSize - 1;
        long contentLength = rangeEnd - rangeStart + 1;

        //读取文件数据
        try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
            raf.seek(rangeStart);
            byte[] data = new byte[(int) contentLength];
            raf.readFully(data);

            //构造HTTP请求
            return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
                    .header(HttpHeaders.ACCEPT_RANGES, "bytes")
                    .header(HttpHeaders.CONTENT_RANGE, "bytes " + rangeStart + "-" + rangeEnd + "/" + fileSize)
                    .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength))
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(new ByteArrayResource(data));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    @RequestMapping("/getFileSize")
    public ResponseEntity<Long> getFileSize(@RequestParam("filename") String filename) {
        LOG.info("filename: {}", filename);
        File file = new File(BASE_DIR + filename);
        if(!file.exists()){
            return ResponseEntity.notFound().build();
        }
        LOG.info("fileSize ：{}",file.length());
        return ResponseEntity.ok(file.length());
    }

}
